package com.ihai.spring.boot.sample.rabbitmq;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * RabbitMQ Config
 *
 * @author 张驰
 * @date 2018/3/2
 */
@Configuration
public class RabbitmqConfig {
    private final static String Q_NAME = "test-mq";
    private final static String EX_NAME = "test-exchange";

    @Bean
    Queue queue() {
        return new Queue(Q_NAME, false);
    }

    @Bean
    TopicExchange exchange() {
        return new TopicExchange(EX_NAME);
    }

    @Bean
    Binding binding(Queue queue, TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(Q_NAME);
    }

    @Bean
    public Provider provider(RabbitTemplate rabbitTemplate){
        return new Provider(rabbitTemplate, EX_NAME, Q_NAME);
    }

    @Bean
    public Receiver receiver(){
        return new Receiver();
    }

    @Bean
    public MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactory,
                                             MessageListenerAdapter listenerAdapter) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(Q_NAME);
        container.setMessageListener(listenerAdapter);
        return container;
    }

}
